package arrray;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author huangxianjin
 * @date 2025/9/1 23:03
 * @description "Z字形变换"
 */
public class LC_6 {
    public static void main(String[] args) {
        LC_6 lc6 = new LC_6();
        lc6.convert("PAYPALISHIRING", 3);
    }

    //自己的做法
    public String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        char[] array = s.toCharArray();
        //游标
        int index = 0;
        int i = 0;
        //最终的结果
        StringBuilder res = new StringBuilder();
        String[] arr = new String[numRows];
        //默认填充空串
        Arrays.fill(arr, "");
        while (i < array.length) {
            while (index < numRows - 1 && i < array.length) {
                arr[index++] += array[i++];
            }
            while (index > 0 && i < array.length) {
                arr[index--] += array[i++];
            }
        }

        for (String str : arr) {
            res.append(str);
        }
        return res.toString();
    }

    //大神做法
    public String convert2(String s, int numRows) {
        if (numRows < 2) return s;
        List<StringBuilder> rows = new ArrayList<StringBuilder>();
        for (int i = 0; i < numRows; i++) rows.add(new StringBuilder());
        int i = 0, flag = -1;
        for (char c : s.toCharArray()) {
            rows.get(i).append(c);
            if (i == 0 || i == numRows - 1) flag = -flag;
            i += flag;
        }
        StringBuilder res = new StringBuilder();
        for (StringBuilder row : rows) res.append(row);
        return res.toString();
    }
}
